package com.shenmazong.demoes00.controller;

import com.shenmazong.demoes00.pojo.TbProduct;
import org.elasticsearch.index.query.MultiMatchQueryBuilder;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.SearchHit;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.query.NativeSearchQuery;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import static org.elasticsearch.index.query.QueryBuilders.matchQuery;
import static org.elasticsearch.index.query.QueryBuilders.multiMatchQuery;

@RestController
public class ElasticSearchController {

    @Autowired
    private ElasticsearchRestTemplate elasticsearchTemplate;

    @PostMapping(value = "/find")
    public Object find(@RequestParam("keyWord") String keyWord) {

        HashMap<String, Object> resultMap = new HashMap<>();

        //Pageable pageable = PageRequest.of(0, 10);

        NativeSearchQuery searchQuery = new NativeSearchQueryBuilder()
                .withQuery(multiMatchQuery(keyWord)
                        .field("name")
                        .field("info")
                        .type(MultiMatchQueryBuilder.Type.BEST_FIELDS))  // 使用匹配度最高的字段的分做整条记录的匹配分数
                //.withSort(SortBuilders.fieldSort("price").order(SortOrder.DESC))
                //.withPageable(pageable)
                .build();
        SearchHits<TbProduct> search = elasticsearchTemplate.search(searchQuery, TbProduct.class);
        System.out.println("搜到："+search.getTotalHits());
        if(search == null) {
            resultMap.put("code", -1);
            resultMap.put("msg", "没有符合的查询结果");
            return resultMap;
        }

        List<TbProduct> products = new ArrayList<TbProduct>();
        for(SearchHit<TbProduct> s : search.getSearchHits()) {
            TbProduct product = s.getContent();
            //System.out.println(product);
            //System.out.println("score="+s.getScore());
            products.add(product);
        }

        resultMap.put("code", 0);
        resultMap.put("products", products);
        resultMap.put("count", search.getTotalHits());
        return resultMap;
    }
}
